package model;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class SimpleCollisionMap implements CollisionMap {

	private boolean[][] collisionGrid;
	
	public SimpleCollisionMap(){
		collisionGrid = new boolean[0][0];
	}
	private SimpleCollisionMap(boolean[][] collGrid){
		collisionGrid = collGrid;
	}
	public SimpleCollisionMap(BufferedImage img){
		//compute bitgrid from a bitmap
		WritableRaster transpRaster = img.getAlphaRaster();
		int width = transpRaster.getWidth();
		int height = transpRaster.getHeight();
		collisionGrid = new boolean[width][height];
		for(int y=0;y<height;y++){
			for(int x=0;x<width;x++){
				collisionGrid[x][y] = transpRaster.getSample(x, y, 0) > 0;
			}
		}
	}
	
	public boolean[][] getCollisionGrid() {
		return collisionGrid;
	}
	
	public String toString(){
		int width = collisionGrid.length;
		if(width>0){
			String returnstr="";
			int height = collisionGrid[0].length;
			for(int y=0;y<height;y++){
				for(int x=0;x<width;x++){
					returnstr+=(collisionGrid[x][y])?1:0;
				}
				returnstr+="\n";
			}
			return returnstr;
		}else return"";
	}
	
	public int getWidth(){
		return collisionGrid.length;
	}
	
	public int getHeight(){
		if(collisionGrid.length>0)
			return collisionGrid[0].length;
		else
			return 0; 
	}
	public int get(int x,int y){
		return (collisionGrid[x][y])?1:0;
	}
	
	public SimpleCollisionMap getExtract(int origx,int origy,int tox,int toy){
		
		boolean[][] collGrid = new boolean[tox-origx][toy-origy];
		for(int x=0;x<tox-origx;x++){
			for(int y=0;y<toy-origy;y++){
				collGrid[x][y] = collisionGrid[origx+x][origy+y];
			}
		}
		
		return new SimpleCollisionMap(collGrid);
	}
}
